package com.mobile.ado.util.ringtone;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.provider.MediaStore;

public class RingtoneUtils {

	public static void setRingtone(Context context, String audioPath) {
		String mimeType = "audio/mp3";
		ContentValues values = getRingtoneContentValue(audioPath, mimeType);
		Uri ringtoneUri = getRingtoneUri(context, audioPath, values);

		RingtoneManager.setActualDefaultRingtoneUri(context,
				RingtoneManager.TYPE_RINGTONE, ringtoneUri);
	}

	private static ContentValues getRingtoneContentValue(String audioPath,
			String mimeType) {
		ContentValues values = new ContentValues();
		values.put(MediaStore.MediaColumns.DATA, audioPath);
		values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
		values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
		values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
		values.put(MediaStore.Audio.Media.IS_ALARM, false);
		values.put(MediaStore.Audio.Media.IS_MUSIC, false);
		values.put(MediaStore.MediaColumns.DATA, audioPath);
		values.put(MediaStore.Audio.Media.DATA, audioPath);
		return values;
	}

	private static Uri getRingtoneUri(Context context, String audioPath,
			ContentValues values) {
		Uri uri = MediaStore.Audio.Media.getContentUriForPath(audioPath);

		Uri newUri = null;

		Cursor cursor = context.getContentResolver().query(uri, null,
				MediaStore.MediaColumns.DATA + "=?",
				new String[] { audioPath }, null);
		if (cursor.moveToFirst() && cursor.getCount() > 0) {
			String id = cursor.getString(0);
			newUri = Uri.withAppendedPath(uri, id);
		}
		if (newUri == null) {
			newUri = context.getContentResolver().insert(uri, values);
		}
		return newUri;
	}

}
